package com.codegero.android.client.sms.gateway.service;

import java.util.List;

import com.codegero.android.client.sms.gateway.entity.RegistryVote;
import com.codegero.android.client.sms.gateway.entity.Response;
import com.codegero.android.client.sms.gateway.entity.Vote;
import com.codegero.android.client.sms.gateway.entity.factory.GatewayDataFactory;
import com.codegero.android.client.sms.gateway.stored.DatabaseManager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;

public class AutoResponseReceiver extends BroadcastReceiver{

	
	@Override
	public void onReceive(Context context, Intent intent) {
		  //---get the SMS message passed in---
		DatabaseManager databaseManager = new DatabaseManager(context);
        Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;         
        if (bundle != null){
            //---retrieve the SMS message received---
        	String noHP ="";
        	String pesan="";
        	Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); 
               	noHP = msgs[i].getOriginatingAddress();
                pesan= pesan + msgs[i].getMessageBody().toString();
            }
            String[]arrPesanSplit=pesan.split(" ");
            if(arrPesanSplit[0].startsWith("r")){
            	List<Response> responses = databaseManager.getAllResponses();
            	for(Response response : responses){
            		if(response.getId().equals(arrPesanSplit[0])){
            		    SmsManager sms=SmsManager.getDefault();
                        sms.sendTextMessage(noHP, null, response.getMessage(), null, null);
            		}
            	}
            }else if(arrPesanSplit[0].startsWith("v")){
            	List<RegistryVote> registryVotes = databaseManager.getAllRegistryVotes(false);
            	for(RegistryVote registryVote:registryVotes){
            		if(registryVote.getId().equals(arrPesanSplit[0])){
            			Vote vote = new Vote();
            			vote.setId(registryVote.getId());
            			vote.setMessage(pesan);
            			int noHp = 0;
            			if(noHP.startsWith("+62")){
            				noHp = Integer.parseInt(noHP.replace("+62", "0"));
            			}else{
            				noHp = Integer.parseInt(noHP);
            			}
            			vote.setNoHp(noHp);
            			databaseManager.addVote(vote);
            		}
            	}
            }
        }
	}
		
	private GatewayDataFactory 	gatewayDataFactory;
}
